from django_redis import get_redis_connection
from redis import RedisError
from rest_framework import serializers

from meiduo.utils.exceptions import logger


class ImageCodeCheckSerializer(serializers.Serializer):
    """
    图片验证检验
    """

    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4,min_length=4)

    def validate(self, attrs):

        image_id = attrs["image_code_id"]
        text = attrs["text"]

        redis_conn = get_redis_connection("verify_codes")
        real_redis_text = redis_conn.get("img_%s"%image_id)
        if not real_redis_text:
            raise serializers.ValidationError("验证码无效")

        try:
            redis_conn.delete("img_%s"%image_id)
        except Exception as e:
            logger.error(e)


        real_redis_text=real_redis_text.decode()


        if text.lower()!=real_redis_text.lower():
            raise serializers.ValidationError("验证码错误")

        mobile = self.context["view"].kwargs["mobile"]
        send_falg = redis_conn.get("send_flag_%s" % mobile)
        if send_falg:
            raise serializers.ValidationError("次数频繁")

        return attrs


